<?php


namespace App\Extensions\Actions\Import;


use App\Extensions\Action;
use App\Models\AdminUser;
use App\Models\Department;
use Carbon\Carbon;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Facades\Excel;

class UserImport extends Action
{
    protected $selector = '.import-post';

    public function handle(Request $request)
    {
        $collect = Excel::toCollection(collect([]), $request->file('file'))->first();
        $user = Admin::user();
        if (!$user['role_type']) {
            return $this->response()->error('没有权限，如有疑问请联系技术人员')->refresh();
        }
        $departments = Department::query()->get();
        $collect = collect($collect)->filter(function ($item, $key) {
            return !empty($item[0]) && !empty($item[1]) && $key;
        })->map(function ($item) {
            foreach ($item as $key => $value) {
                $item[$key] = trim($value);
            }
            return $item;
        })->values()->map(function ($row) use ($departments, $user) {
            if ($user['role_type'] == 2) {
                $department_id = $user['department_id'];
            } else {
                $dept = $departments->where('name', $row[2])->first();
                $department_id = $dept['id'] ?? 0;
            }
            $password = $row[6] ?: 123456;
            return [
                'key'   => $row[0],
                'value' => [
                    'username'       => $row[0],
                    'name'           => $row[1],
                    'department_id'  => $department_id,
                    'mobile'         => $row[3] ?: null,
                    'education'      => $row[4],
                    'academic_title' => $row[5],
                    'password'       => Hash::make($password),
                    'role_type'      => 0,
                    'created_at'     => Carbon::now(),
                    'updated_at'     => Carbon::now(),
                ]
            ];
        })->pluck('value', 'key')->values();
        $res = AdminUser::query()->whereIn('username', $collect->pluck('username'))->pluck('username')->toArray();
        if ($res) {
            $msg = implode(",", $res);
            return $this->response()->swal()->error("工号已存在:\n" . $msg)->refresh();
        }
        if ($collect) {
            AdminUser::query()->insert($collect->all());
        }
        return $this->response()->success('导入成功')->refresh();
    }

    public function form()
    {
        $this->file('file', '请选择文件')
            ->help('<a target="_blank" href="' . url('/template/teachers_student_template.xls') . '" download="职工账号导入模板.xls">职工账号导入模板</a>');
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-instagram import-post">批量导入账号</a>
HTML;
    }
}
